package com.cotacao;

import java.util.ArrayList;
import java.util.List;

import com.controller.ProdutoMarcaController;
import com.dao.ProdutoMarcaDao;
import com.database.TransactionManager;
import com.model.ProdutoMarcaBean;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class Marca extends Activity {

	private Intent i;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		final TransactionManager transaction = new TransactionManager(getApplicationContext());
		transaction.start();
		setContentView(R.layout.activity_marca);
		Button btn = (Button) findViewById(R.id.voltar);
		Button btn1 = (Button) findViewById(R.id.cadastrar);
		i = new Intent(this, Cotacao.class);
		TableView(transaction);
		btn1.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				EditText et = (EditText)findViewById(R.id.nomemarca);
				String nome = 	et.getText().toString();
				ProdutoMarcaController ctr = new ProdutoMarcaController();
				try {
					ctr.inserir(transaction, nome);
					transaction.commit();
					et.setText("");
					//					Toast.makeText(this, "Registro salvo com sucesso", Toast.LENGTH_LONG).show();
				} catch (Exception e) {
					Log.d("ERROR", e.getMessage());
					transaction.rollback();
				}finally{
					finish();				
				}
			}
		});

		btn.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				transaction.rollback();
				finish();				
			}
		});
	}
	protected void TableView(TransactionManager transaction) {
		ProdutoMarcaDao dao = new ProdutoMarcaDao();
		List<ProdutoMarcaBean> marList = dao.getAll(transaction);

		ArrayList<String> list = new ArrayList<String>();
		for (ProdutoMarcaBean Bean : marList) {
			list.add(Bean.getDescricao());
		}

		ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
		ListView listView = (ListView) findViewById(R.id.listView1);
		listView.setAdapter(arrayAdapter);
		OnItemClickListener listener = new OnItemClickListener() {

			public void onItemClick(AdapterView<?> adp, View v,	int pos, long id) {
				Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT ).show();
			}
		};
		listView.setOnItemClickListener(listener);
	}
}
